package com.example.cognitivesystemserver.service;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.cognitivesystemserver.Model.UserModel;
import com.example.cognitivesystemserver.mapper.LoginMapper;
import com.example.cognitivesystemserver.mapper.StudentMapper;
import com.example.cognitivesystemserver.mapper.TeacherMapper;
import com.example.cognitivesystemserver.pojo.Login;
import com.example.cognitivesystemserver.pojo.Student;
import com.example.cognitivesystemserver.pojo.Teacher;
import com.example.cognitivesystemserver.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService{
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private StudentMapper studentMapper;


    @Override
    public UserModel register(String name, String userId, String userPwd, String role) {
        checkLoginParams(userId,userPwd);
        AssertUtil.isTrue(loginMapper.queryLoginById(userId)!=null,"用户已存在");

        if("1".equals(role)){
            Teacher teacher=new Teacher();
            teacher.setName(name);
            teacher.setTeacherId(userId);
            teacherMapper.addTeacher(teacher);
        }

        if("2".equals(role)){
            Student student=new Student();
            student.setName(name);
            student.setStuId(userId);
            studentMapper.addStudent(student);
        }
        Login login=new Login();
        login.setName(name);
        login.setUserId(userId);
        login.setPassword(userPwd);
        login.setRole(role);
        loginMapper.insert(login);

        return buildUserInfo(login);

    }

    @Override
    public UserModel login(String userId,String userPwd,String role) {
        //checkLoginParams(userId,userPwd);

       Login login=loginMapper.queryLoginById(userId);

        AssertUtil.isTrue(login.getUserId()==null,"用户姓名不存在");
        //做密码校验
        AssertUtil.isTrue(login.getPassword()==null,"用户密码不存在");
        //校验密码与用户是否匹配
        if (login.getPassword().equals(userPwd)){
            //如果匹配设置用户对象，传入设置token
            String token=getToken(login,24*60* 60 * 1000);
            String refreshToken =getToken(login, 24*60*60*1000); // 有效期一天

            //设置返回对象
            UserModel userModel=new UserModel();
            userModel.setUserId(login.getUserId());
            userModel.setToken(token);
            userModel.setRefreshToken(refreshToken);
            buildUserInfo(login);
            if("0".equals(role)){

                login= loginMapper.queryLoginByAdId(userId);
            }
            else if("1".equals(role)){
                login= loginMapper.queryLoginByTeaId(userId);
            }
            else if("2".equals(role)){
                login= loginMapper.queryLoginByStuId(userId);
            }
            userModel.setName(login.getName());
            userModel.setLevel(role);
            return userModel;

        }else {
            //密码不匹配
            return null;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePassWord(String userId, String oldPwd, String newPwd, String repeatPwd) {

        Login login =loginMapper.queryLoginById(userId);
        AssertUtil.isTrue(null==login,"待更新记录不存在");
        //参数校验
        checkPasswordParams(login,oldPwd,newPwd,repeatPwd);
        login.setPassword(newPwd);
        AssertUtil.isTrue(loginMapper.updateByPrimaryKeySelective(login)<1,"修改密码失败");


    }

    private UserModel buildUserInfo(Login login){
        UserModel userModel=new UserModel();

        userModel.setUserId(login.getUserId());
        userModel.setName(login.getName());


        //int role= login.getRole();
       /* if(role==1){
            userModel.setUserName("管理员");
        }

        if(role==2){
            userModel.setUserName("教师");
        }

        if(role==3){
            userModel.setUserName("学生");
        }*/
        return userModel;
    }

    private void checkLoginParams(String userId, String userPwd) {
        //验证用户id
        AssertUtil.isTrue(StringUtils.isBlank(userId),"用户姓名不能为空！");

        //验证用户密码
        AssertUtil.isTrue(StringUtils.isBlank(userPwd),"用户密码不能为空！");

    }
    private void checkPasswordParams(Login login,String oldPwd,String newPwd,String repeatPwd){
        AssertUtil.isTrue(StringUtils.isBlank(oldPwd),"原始密码不能为空");
        AssertUtil.isTrue(!login.getPassword().equals(oldPwd),"原始密码不正确");

        AssertUtil.isTrue(StringUtils.isBlank(newPwd),"新密码不能为空！");
        AssertUtil.isTrue(oldPwd.equals(newPwd),"新密码不能与原始密码相同！");

        AssertUtil.isTrue(StringUtils.isBlank(repeatPwd),"确认密码不能为空");
        AssertUtil.isTrue(!newPwd.equals(repeatPwd),"新密码与新密码不一致！");


    }

    public List<Login> selectByUserId(String userId)throws DataAccessException {
        List<Login> loginList = loginMapper.LoginById(userId);
        return loginList;
    }
    @Override
    public String getToken(Login login, long time) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + time;//一小时有效时间
        Date end = new Date(currentTime);
        String token = "";
        token = JWT.create().withAudience(Integer.valueOf(login.getRole()).toString()+login.getId().toString()).withIssuedAt(start).withExpiresAt(end)
                // 储存id和level
                .sign(Algorithm.HMAC256(login.getPassword())); // 储存password，用于解密
        return token;
    }
}
